package bjtu.cit.bookshop.service.impl;

import bjtu.cit.bookshop.daos.BookMapper;
import bjtu.cit.bookshop.daos.OrderBookMapper;
import bjtu.cit.bookshop.daos.OrderMapper;
import bjtu.cit.bookshop.entities.Order;
import bjtu.cit.bookshop.entities.OrderBook;
import bjtu.cit.bookshop.service.IOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by jia19 on 2015/9/23.
 */
@Service("orderService")
public class OrderServiceImpl implements IOrderService {

    @Resource
    private OrderMapper orderMapper = null;

    @Resource
    private OrderBookMapper orderBookMapper = null;

    @Resource
    private BookMapper bookMapper = null;

    @Override
    public int createAOrder(Order order, List<OrderBook> books) {
        this.orderMapper.insertSelective(order);
        int orderId = order.getId();
        for (OrderBook book : books) {
            book.setOrderid(orderId);
            orderBookMapper.insertSelective(book);
        }
        return 1;
    }

    @Override
    public Order getOrderById(int id) {
        return this.orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Order> getOrderListByUserId(int id) {
        return this.orderMapper.selectByUserId(id);
    }

    @Override
    public int getLength() {
        return this.orderMapper.selectOrderList().size();
    }

    @Override
    public List<Order> getOrderList(int num, int offset) {
        List<Order> list = this.orderMapper.selectOrderList();

        int endIndex = offset + num;
        if (offset >= list.size()) {
            return null;
        }
        if (endIndex >= list.size()) {
            endIndex = list.size();
        }
        return list.subList(offset, endIndex);
    }

    @Override
    public List<OrderBook> getBookListByOrderId(int id) {
        Order order = this.orderMapper.selectByPrimaryKey(id);
        List<OrderBook> books = this.orderBookMapper.selectListByOrderId(id);
        return books;
    }

    @Override
    public int updateOrder(Order order) {
        return this.orderMapper.updateByPrimaryKeySelective(order);
    }
}
